/**
 * @program: PavtFirmware
 * @description:
 * @author: zyc
 * @create: 2018-06-08 14:42
 **/
package com.zjpavt.client.command;

import com.zjpavt.client.Connection;
import com.zjpavt.client.event.EventRegisterCenter;
import com.zjpavt.client.hal.LoopManager;
import com.zjpavt.client.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 主动推送数据到服务器
 */

public class CommandPusher {
    private static final Logger log = LoggerFactory.getLogger(CommandPusher.class);
    static void push(Connection conn, String msg2Server) {
        conn.appendMsgToQueue(msg2Server);
    }
    public static void init() {

    }
    /**
     * 当回路状态改变时推送当前回路状态
     */
    private static final LoopManager.OnLoopChangeListener LOOP_LISTENER =
        ()-> jCommandPush(Connection.getInstance());

    static {
        log.info("CommandPusher static");
        LoopManager.getInstance().addLoopListener(LOOP_LISTENER);
    }
    public static String previousLoopStatus ="";
    public static void jCommandPush(Connection conn) {
        String prefix = "<J_";
        int[] status = LoopManager.getInstance().getEighthLoopStatus();
        Map<String, Object> loopStatus = new HashMap<>();
        loopStatus.put(EventRegisterCenter.LOOP_STATUS, StringUtil.commandInt2String(status));
        EventRegisterCenter.getInstance().triggerRegisterTask(EventRegisterCenter.LOOP_CHANGE,loopStatus);
        String msg = StringUtil.commandInt2String(status);
        if (!msg.isEmpty()) {
            if (!msg.equals(previousLoopStatus)) {
                previousLoopStatus = msg;
                push(conn, prefix + msg +">");
            } else {
                log.debug("status is not change acture");
            }
        } else {
            log.warn("jCommandPush null");
        }
    }

    /**
     * 推送告警信息
     * @param conn
     * @param msg
     */
    public static void AlarmPush(Connection conn, String msg) {
        if (!msg.isEmpty()) {
            push(conn, msg);
        } else {
            log.warn("AlarmPush null");
        }
    }
}
